/**
 * 状态管理Store - 简化版
 * 基于Pinia实现的状态管理，提供基础CRUD操作
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type {
  StateCreate,
  StateUpdate,
  ModuleStateResponse,
  ModuleType,
  StateResponse
} from '@/types/state'
import type { StateResponse as ApiStateResponse } from '@/api/state'
import { StateAPI } from '@/api/state'

export const useStateStore = defineStore('state', () => {
  // ============= 响应式状态 =============
  
  const states = ref<StateResponse[]>([])

  const normalizeState = (raw: ApiStateResponse): StateResponse => {
    const extendedRaw = raw as ApiStateResponse & { created_by?: string; updated_by?: string }
    return {
      id: raw.id,
      name: raw.name,
      code: raw.code,
      module_type: raw.module_type as ModuleType,
      description: raw.description,
      color: raw.color || '#909399',
      icon: raw.icon,
      sort_order: raw.sort_order,
      is_enabled: raw.is_enabled,
      is_visible: raw.is_visible,
      is_default: raw.is_default,
      created_at: raw.created_at,
      updated_at: raw.updated_at,
      created_by: extendedRaw.created_by,
      updated_by: extendedRaw.updated_by
    }
  }
  const loading = ref(false)
  const error = ref<string | null>(null)
  // 模块状态加载状态缓存，避免重复请求
  const moduleStatesLoaded = ref<Set<ModuleType>>(new Set())
  const moduleStatesLoading = ref<Map<ModuleType, Promise<ModuleStateResponse>>>(new Map())

  // ============= 计算属性 =============
  
  /**
   * 按模块分组的状态
   */
  const statesByModule = computed(() => {
    const result: Record<string, StateResponse[]> = {}
    
    // 确保states.value是数组
    if (!Array.isArray(states.value)) {
      console.warn('states.value is not an array:', states.value)
      return result
    }
    
    states.value.forEach((state: StateResponse) => {
      if (!result[state.module_type]) {
        result[state.module_type] = []
      }
      result[state.module_type].push(state)
    })
    
    // 对每个模块的状态按排序顺序排序
    Object.keys(result).forEach(moduleType => {
      result[moduleType] = result[moduleType].sort((a, b) => a.sort_order - b.sort_order)
    })
    
    return result
  })

  /**
   * 启用状态列表
   */
  const enabledStates = computed(() => 
    Array.isArray(states.value) ? states.value.filter(state => state.is_enabled) : []
  )

  /**
   * 可见状态列表
   */
  const visibleStates = computed(() => 
    Array.isArray(states.value) ? states.value.filter(state => state.is_visible) : []
  )

  // ============= 状态查询方法 =============
  
  /**
   * 根据ID获取状态
   */
  const getStateById = (stateId: string): StateResponse | undefined => {
    return Array.isArray(states.value) ? states.value.find(state => state.id === stateId) : undefined
  }

  /**
   * 根据代码获取状态
   */
  const getStateByCode = (code: string, moduleType?: ModuleType): StateResponse | undefined => {
    return Array.isArray(states.value) ? states.value.find(state => 
      state.code === code && (!moduleType || state.module_type === moduleType)
    ) : undefined
  }

  /**
   * 获取模块的状态列表
   */
  const getStatesByModule = (moduleType: ModuleType): StateResponse[] => {
    return statesByModule.value[moduleType] || []
  }

  /**
   * 获取模块的默认状态
   */
  const getDefaultStateByModule = (moduleType: ModuleType): StateResponse | undefined => {
    return Array.isArray(states.value) ? states.value.find(state => 
      state.module_type === moduleType && state.is_default
    ) : undefined
  }

  // ============= API调用方法 =============
  
  /**
   * 获取状态列表
   */
  const fetchStates = async (params?: {
    module_type?: ModuleType
    is_enabled?: boolean
    is_visible?: boolean
    search?: string
    skip?: number
    limit?: number
  }): Promise<StateResponse[]> => {
    loading.value = true
    error.value = null
    
    try {
      const response = await StateAPI.getStates(params)
      const payload: any = response && typeof response === 'object' && 'data' in response
        ? (response as any).data
        : response
      let rawStates: ApiStateResponse[] = []

      if (Array.isArray(payload)) {
        rawStates = payload as ApiStateResponse[]
      } else if (payload && typeof payload === 'object') {
        if (Array.isArray(payload.data)) {
          rawStates = payload.data as ApiStateResponse[]
        } else if (Array.isArray(payload.items)) {
          rawStates = payload.items as ApiStateResponse[]
        } else if (Array.isArray(payload.states)) {
          rawStates = payload.states as ApiStateResponse[]
        }
      }

      const normalizedStates = rawStates.map(normalizeState)

      if (params?.module_type) {
        const filteredStates = states.value.filter(state => state.module_type !== params.module_type)
        states.value = [...filteredStates, ...normalizedStates]
      } else {
        states.value = normalizedStates
      }

      return normalizedStates
    } catch (err: any) {
      const errorMessage = err instanceof Error ? err.message : (err?.message || '获取状态列表失败')
      error.value = errorMessage
      console.error('获取状态列表失败:', err)
      // 不抛出错误，返回空数组避免中断流程
      return []
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取状态详情
   */
  const fetchState = async (stateId: string): Promise<StateResponse> => {
    loading.value = true
    error.value = null
    
    try {
      const response = await StateAPI.getState(stateId)
      const payload: any = response && typeof response === 'object' && 'data' in response
        ? (response as any).data
        : response
      const state = normalizeState(payload as ApiStateResponse)
      
      const index = states.value.findIndex(s => s.id === stateId)
      if (index !== -1) {
        states.value[index] = state
      } else {
        states.value.push(state)
      }
      
      return state
    } catch (err: any) {
      error.value = err.message || '获取状态详情失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 创建状态
   */
  const createState = async (stateData: StateCreate): Promise<StateResponse> => {
    loading.value = true
    error.value = null
    
    try {
      const response = await StateAPI.createState(stateData)
      const payload: any = response && typeof response === 'object' && 'data' in response
        ? (response as any).data
        : response
      const state = normalizeState(payload as ApiStateResponse)
      
      states.value.push(state)
      
      return state
    } catch (err: any) {
      error.value = err.message || '创建状态失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 更新状态
   */
  const updateState = async (stateId: string, stateData: StateUpdate): Promise<StateResponse> => {
    loading.value = true
    error.value = null
    
    try {
      const rawState = await StateAPI.updateState(stateId, stateData)
      const updatedState = normalizeState(rawState as ApiStateResponse)
      
      const index = states.value.findIndex(state => state.id === stateId)
      if (index !== -1) {
        states.value[index] = updatedState
      } else {
        states.value.push(updatedState)
      }
      
      moduleStatesLoaded.value.delete(updatedState.module_type)
      
      return updatedState
    } catch (err: any) {
      const errorMsg = err?.response?.data?.message || err?.message || '更新状态失败'
      error.value = errorMsg
      throw new Error(errorMsg)
    } finally {
      loading.value = false
    }
  }

  /**
   * 删除状态
   */
  const deleteState = async (stateId: string): Promise<void> => {
    loading.value = true
    error.value = null
    
    try {
      await StateAPI.deleteState(stateId)
      
      // 从本地状态列表中移除
      if (Array.isArray(states.value)) {
        const index = states.value.findIndex(state => state.id === stateId)
        if (index !== -1) {
          states.value.splice(index, 1)
        }
      }
    } catch (err: any) {
      error.value = err.message || '删除状态失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取模块状态
   * @param moduleType 模块类型
   * @param forceRefresh 是否强制刷新（默认false，如果已加载过则使用缓存）
   */
  const fetchModuleStates = async (moduleType: ModuleType, forceRefresh = false): Promise<ModuleStateResponse> => {
    // 如果已加载且不是强制刷新，检查是否有进行中的请求
    if (!forceRefresh && moduleStatesLoaded.value.has(moduleType)) {
      const existingPromise = moduleStatesLoading.value.get(moduleType)
      if (existingPromise) {
        // 如果有正在进行的请求，等待它完成
        await existingPromise
        // 返回缓存的数据
        const moduleStates = getStatesByModule(moduleType)
        return {
          module_type: moduleType,
          states: moduleStates,
          total_count: moduleStates.length
        } as ModuleStateResponse
      }
      // 如果已加载且没有进行中的请求，直接返回缓存的数据
      const moduleStates = getStatesByModule(moduleType)
      if (moduleStates.length > 0) {
        return {
          module_type: moduleType,
          states: moduleStates,
          total_count: moduleStates.length
        } as ModuleStateResponse
      }
    }
    
    // 检查是否有正在进行的请求
    const existingPromise = moduleStatesLoading.value.get(moduleType)
    if (existingPromise) {
      // 如果有正在进行的请求，等待它完成而不是发起新请求
      await existingPromise
      const moduleStates = getStatesByModule(moduleType)
      return {
        module_type: moduleType,
        states: moduleStates,
        total_count: moduleStates.length
      } as ModuleStateResponse
    }
    
    // 创建新的请求Promise
    loading.value = true
    error.value = null
    
    const requestPromise = (async () => {
    try {
      console.log(`开始获取模块 ${moduleType} 的状态...`)
      const response = await StateAPI.getModuleStates(moduleType)
      console.log(`模块 ${moduleType} 的API响应:`, response)
        
        let rawModuleStates: ApiStateResponse[] = []

        if (Array.isArray(response)) {
          rawModuleStates = response as ApiStateResponse[]
        } else if (response && typeof response === 'object' && 'data' in response) {
          const responseData = (response as any).data
          if (responseData && typeof responseData === 'object') {
            if (responseData.success && Array.isArray(responseData.data)) {
              rawModuleStates = responseData.data as ApiStateResponse[]
            } else if (Array.isArray(responseData)) {
              rawModuleStates = responseData as ApiStateResponse[]
            } else if (responseData.states && Array.isArray(responseData.states)) {
              rawModuleStates = responseData.states as ApiStateResponse[]
            }
          } else if (Array.isArray(responseData)) {
            rawModuleStates = responseData as ApiStateResponse[]
          }
        } else if (response && typeof response === 'object' && 'states' in response) {
          const responseWithStates = response as { states?: unknown }
          if (Array.isArray(responseWithStates.states)) {
            rawModuleStates = responseWithStates.states as ApiStateResponse[]
          }
        }

        const moduleStates = rawModuleStates.map(normalizeState)
      
      console.log(`解析后的模块 ${moduleType} 状态数量:`, moduleStates.length)
      
      // 更新本地状态列表中对应模块的状态
      if (Array.isArray(states.value)) {
        // 移除该模块的旧状态
        states.value = states.value.filter(state => state.module_type !== moduleType)
        // 添加新状态
        if (moduleStates.length > 0) {
        states.value.push(...moduleStates)
          console.log(`模块 ${moduleType} 的状态已更新，当前总状态数:`, states.value.length)
        }
      }
      
        // 标记该模块状态已加载
        moduleStatesLoaded.value.add(moduleType)
        
        return {
          module_type: moduleType,
          states: moduleStates,
          total_count: moduleStates.length
        }
    } catch (err: any) {
      error.value = err.message || '获取模块状态失败'
        // 请求失败时移除加载标记，允许重试
        moduleStatesLoaded.value.delete(moduleType)
      throw err
    } finally {
      loading.value = false
        // 请求完成后移除进行中的标记
        moduleStatesLoading.value.delete(moduleType)
      }
    })()
    
    // 保存请求Promise，以便其他组件可以等待同一个请求
    moduleStatesLoading.value.set(moduleType, requestPromise)
    
    return requestPromise
  }

  /**
   * 初始化模块状态
   */
  const initModuleStates = async (moduleType: ModuleType): Promise<{
    created: StateResponse[]
    updated: StateResponse[]
    disabled: string[]
    created_count: number
    updated_count: number
    disabled_count: number
  }> => {
    loading.value = true
    error.value = null
    
    try {
      const result = await StateAPI.initModuleStates(moduleType)
      // 处理API响应格式
      let payload: {
        created?: unknown
        updated?: unknown
        disabled?: unknown
        created_count?: number
        updated_count?: number
        disabled_count?: number
      } | null = null
      
      if (result && typeof result === 'object') {
        if ('data' in result && result.data) {
          payload = result.data as typeof payload
        } else {
          payload = result as typeof payload
        }
      }
      
      if (!payload) {
        throw new Error('无效的响应格式')
      }

      const createdStates = Array.isArray(payload?.created)
        ? (payload.created as ApiStateResponse[]).map(normalizeState)
        : []
      const updatedStates = Array.isArray(payload?.updated)
        ? (payload.updated as ApiStateResponse[]).map(normalizeState)
        : []
      const disabledStates = Array.isArray(payload?.disabled) ? payload.disabled : []

      const responseData = {
        created: createdStates,
        updated: updatedStates,
        disabled: disabledStates,
        created_count: payload?.created_count ?? createdStates.length,
        updated_count: payload?.updated_count ?? updatedStates.length,
        disabled_count: payload?.disabled_count ?? disabledStates.length
      }
      
      // 初始化成功后，直接刷新所有状态数据
      await fetchStates()
      
      return responseData
    } catch (err: any) {
      error.value = err.message || '初始化模块状态失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 清除错误
   */
  const clearError = (): void => {
    error.value = null
  }

  /**
   * 重置store状态
   */
  const reset = (): void => {
    states.value = []
    loading.value = false
    error.value = null
    moduleStatesLoaded.value.clear()
    moduleStatesLoading.value.clear()
  }
  
  /**
   * 刷新所有状态数据
   */
  const refreshStates = async (): Promise<void> => {
    // 清除模块加载缓存，强制重新加载
    moduleStatesLoaded.value.clear()
    moduleStatesLoading.value.clear()
    await fetchStates()
  }
  
  /**
   * 清除模块状态缓存
   */
  const clearModuleCache = (moduleType?: ModuleType): void => {
    if (moduleType) {
      moduleStatesLoaded.value.delete(moduleType)
      moduleStatesLoading.value.delete(moduleType)
    } else {
      moduleStatesLoaded.value.clear()
      moduleStatesLoading.value.clear()
    }
  }

  return {
    // 状态
    states,
    loading,
    error,
    
    // 计算属性
    statesByModule,
    enabledStates,
    visibleStates,
    
    // 查询方法
    getStateById,
    getStateByCode,
    getStatesByModule,
    getDefaultStateByModule,
    
    // API方法
    fetchStates,
    fetchState,
    createState,
    updateState,
    deleteState,
    fetchModuleStates,
    initModuleStates,
    
    // 工具方法
    clearError,
    reset,
    refreshStates,
    clearModuleCache
  }
})